package classes.utils.trtb.xmlLoader
{
	import flash.net.URLVariables;
	import classes.utils.trtb.xmlLoader.XMLLoaderEvent;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLStream;
	import flash.events.*;
	
	
	public class XMLLoader extends EventDispatcher{
		
		private var loader: URLStream = new URLStream();
		private var urlRequest:URLRequest = new URLRequest();
		private var _xml: XML;
		public var encode: String = "utf-8";
		public var url: String;
		
		public function XMLLoader() {
			this.loader.addEventListener( Event.COMPLETE, loadComplete );
			this.loader.addEventListener( IOErrorEvent.IO_ERROR, loadFailIO );
			this.loader.addEventListener( SecurityErrorEvent.SECURITY_ERROR, loadFailSecurity );
			//this.loader.addEventListener( ProgressEvent.PROGRESS, loadProgress );
		}
		
		public function load( _params:URLVariables = null): void {
			//trace("_params : " , _params.toString() );
			if( this.url == null || this.url == "" ){
				this.loadFailIO( new IOErrorEvent( IOErrorEvent.IO_ERROR ) );
				return;
			}
			
			if ( _params ) {
				urlRequest.url = url;
				urlRequest.data = _params;
				urlRequest.method = URLRequestMethod.POST;
			}else{
				urlRequest.url = url;
			}
			this.loader.load( urlRequest );
		}
		
		private function loadComplete( e: Event ): void {
			//this.loader.removeEventListener( Event.COMPLETE, loadComplete );
			//this.loader.removeEventListener( IOErrorEvent.IO_ERROR, loadFailIO );
			//this.loader.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, loadFailSecurity );
			
			try{
				this._xml = XML( this.loader.readMultiByte( this.loader.bytesAvailable, this.encode ) );
			}
			catch( e: TypeError ){
				this.dispatchEvent( new XMLLoaderEvent( XMLLoaderEvent.LOAD_FAIL, "parse error" ) );
				return;
			}
			
			this.dispatchEvent( new XMLLoaderEvent( XMLLoaderEvent.LOAD_COMPLETE ) );
		}
		
		private function loadProgress( e: ProgressEvent ): void {
			//this.dispatchEvent( e.clone() );
		}
		
		private function loadFailSecurity( e: Event ): void {
			this.loader.removeEventListener( Event.COMPLETE, loadComplete );
			this.loader.removeEventListener( IOErrorEvent.IO_ERROR, loadFailIO );
			this.loader.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, loadFailSecurity );
			
			this.dispatchEvent( new XMLLoaderEvent( XMLLoaderEvent.LOAD_FAIL, "Security Error." ) );
		}
		
		private function loadFailIO( e: Event ): void {
			this.loader.removeEventListener( Event.COMPLETE, loadComplete );
			this.loader.removeEventListener( IOErrorEvent.IO_ERROR, loadFailIO );
			this.loader.removeEventListener( SecurityErrorEvent.SECURITY_ERROR, loadFailSecurity );
			
			this.dispatchEvent( new XMLLoaderEvent( XMLLoaderEvent.LOAD_FAIL, "File IOError." ) );
		}
		
		public function get xml(): XML{
			return this._xml;
		}
	}
}